﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;
using Gin.Transactions;

namespace Gin.Commands
{
    [GinName( Name = "ВыполнитьЕсли-Иначе", Description = "Условный оператор if-then-else", Group = "Управление пакетом")]
    public class ExecuteIf : TransactionalCommand, IContainerCommand
    {
        [GinArgumentText(Multiline = false, MaxLength = 500)]
        public string ArgumentName { get; set; }

        [GinArgumentCommand(AllowMultiple = false)]
        public Command Then { get; set; }

        [GinArgumentCommand(AllowMultiple = false)]
        public Command Else { get; set; }

        public override void Do(ExecutionContext context)
        {
            if ((bool)context.GetResult(ArgumentName))
            {
                Then.Do(context);
            }
            else if (Else != null)
            {
                Else.Do(context);
            }
        }

        public override TransactionStep Do(ExecutionContext context, Transactions.Transaction transaction)
        {
            if ((bool)context.GetResult(ArgumentName))
            {
                if (Then is TransactionalCommand)
                {
                    ((TransactionalCommand)Then).Do(context, transaction);
                }
                else
                {
                    Then.Do(context);
                }
            }
            return null;
        }

        public override void Rollback(TransactionStep step)
        {
        }

        public IEnumerable<Command> InnerCommands
        {
            get
            {
                List<Command> list = new List<Command>();
                if (Then != null)
                {
                    list.Add(Then);
                }
                if (Else != null)
                {
                    list.Add(Else);
                }
                return list;
            }
        }
    }
}
